/**
 * 文件名：****.java
 * 版权：Copyright Lightkit All Rights Reserved.
 * 描述：*****
 */
package com.lightkits.wms.domain.allot.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.lightkits.common.db.entity.BdTag;
import com.lightkits.common.db.entity.FndOrganizationBase;
import com.lightkits.common.db.entity.FndWmMoveTypeBase;
import com.lightkits.common.db.entity.WmExecuteLine;
import com.lightkits.common.db.entity.WmRequestHeader;
import com.lightkits.common.db.entity.WmRequestLine;
import com.lightkits.framework.common.model.CheckResult;
import com.lightkits.framework.common.utility.object.ObjectUtil;
import com.lightkits.framework.common.utility.object.ParseUtil;
import com.lightkits.wms.client.DocumentServiceClient;
import com.lightkits.wms.domain.allot.CreateDocParamsService;
import com.lightkits.wms.domain.allot.model.AllotConstrants;
import com.lightkits.wms.domain.deliveryorder.service.CreateDeliveryOrderDomain;
import com.lightkits.wms.domain.saleticket.model.SaleConstrant;
import com.lightkits.wms.dto.allot.model.PickHeadDto;
import com.lightkits.wms.dto.allot.model.PickLineDto;
import com.lightkits.wms.dto.document.GenerateDocNumRequestType;
import com.lightkits.wms.dto.document.GenerateDocNumResponseType;
import com.lightkits.wms.util.models.Constrants;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * CreateDocParamsServiceImpl
 *
 * @author jing.wei@hand-china.com
 * Created on 2019/5/23 11:14
 */
@Service
public class CreateDocParamsServiceImpl implements CreateDocParamsService {

    private final CreateDeliveryOrderDomain createDeliveryOrderDomain;

    private static final int SIZE = 5;

    @Autowired
    public CreateDocParamsServiceImpl(CreateDeliveryOrderDomain createDeliveryOrderDomain, DocumentServiceClient client) {
        this.createDeliveryOrderDomain = createDeliveryOrderDomain;
        this.client = client;
    }
    private final DocumentServiceClient client;

    /**
     * 创建领料单头
     *
     * @param dto 调拨发出请求头参数
     * @return WmRequestHeader
     **/
    @Override
    public CheckResult<WmRequestHeader> createRequestHeader(PickHeadDto dto) {
        CheckResult<WmRequestHeader> checkResult = new CheckResult<>();
        checkResult.setSuccessful(true);
        WmRequestHeader header = new WmRequestHeader();
        SimpleDateFormat df = new SimpleDateFormat("yyyyMMdd");
        GenerateDocNumRequestType request = new GenerateDocNumRequestType();
        request.setCount(1);
        request.setSize(SIZE);
        request.setType("WR");
        request.setField1(df.format(new Date()));
        GenerateDocNumResponseType response = client.generateDocNumber(request);
        header.setRequestNum(response.getDocNumList().get(0));
        header.setOrganizationId(ParseUtil.tryLongWithException(dto.getOrgId()));
        FndOrganizationBase base = new FndOrganizationBase().selectById(header.getOrganizationId());
        header.setEnterpriseId(base.getParentOrganizationId());
        base = new FndOrganizationBase().selectById(dto.getToOrganzationId());
        header.setToEnterpriseId(base.getParentOrganizationId());
        header.setOperationType(AllotConstrants.OPERATION_TYPE);
        header.setCreatorId(ParseUtil.tryLongWithException(dto.getCreatorId()));
        header.setProcessStatus(AllotConstrants.PROCESS_STATUS);
        header.setRequestType(AllotConstrants.REQUEST_TYPE);
        if (!ObjectUtil.isNullOrEmpty(dto.getInternalSettlementPrice())) {
            header.setInternalSettlementPrice(new BigDecimal(dto.getInternalSettlementPrice()));
        }
        header.setOuterRequestNum(dto.getOuterRequestNum());
        header.setRemark(dto.getRemark());
        header.setRequestWorker(dto.getRequestWorker());
        //移动类型固定为调拨"WM_ALLOT"
        FndWmMoveTypeBase moveTypeBase = new FndWmMoveTypeBase()
                .selectOne(new EntityWrapper()
                        .eq(FndWmMoveTypeBase.MOVE_TYPE_CODE, AllotConstrants.MOVE_WM_ALLOT));
        header.setWmMoveTypeId(moveTypeBase.getId());
        if (!ObjectUtil.isNullOrEmpty(dto.getRequestWorkerId())) {
            header.setRequestWorkerId(ParseUtil.tryLongWithException(dto.getRequestWorkerId()));
        }
        if (!ObjectUtil.isNullOrEmpty(dto.getToOrganzationId())) {
            header.setToOrganizationId(ParseUtil.tryLongWithException(dto.getToOrganzationId()));
        }
        checkResult.setData(header);
        return checkResult;
    }

    /**
     * 创建领料单行
     *
     * @param lineDTOS 调拨发出请求行信息
     * @param headerId 领料单头Id
     * @return WmRequestLine
     **/
    @Override
    public CheckResult<List<WmRequestLine>> createRequestLines(List<PickLineDto> lineDTOS,
                                                               Long headerId) {
        CheckResult<List<WmRequestLine>> checkResult = new CheckResult<>();
        checkResult.setSuccessful(true);
        List<WmRequestLine> lines = new ArrayList<>();
        int num = 1;
        for (PickLineDto dto : lineDTOS) {
            WmRequestLine line = new WmRequestLine();
            line.setLineNum(new Long(num));
            line.setRequestId(headerId);
            line.setItemId(ParseUtil.tryLongWithException(dto.getItemId()));
            line.setUom(dto.getUomCode());
            line.setWarehouseId(ParseUtil.tryLongWithException(dto.getFromWarehouseId()));
            line.setToWarehouseId(ParseUtil.tryLongWithException(dto.getToWarehouseId()));
            line.setViaWarehouseId(ParseUtil.tryLongWithException(dto.getViaWarehouseId()));
            line.setApplyQty(new BigDecimal(dto.getApplyQty()));
            line.setLineStatus(AllotConstrants.PROCESS_STATUS);
            num += 1;
            line.setRemark(dto.getRemark());
            line.setOwnerType(Constrants.OWN);
            line.setPickedFlag(true);
            line.setTagCode(dto.getTagCode());
            line.setPickedQty(line.getApplyQty());
            line.setExeutedQty(line.getApplyQty());
            line.setLotNumber(line.getLotNumber());
            line.setTagCode(line.getTagCode());
            if (!ObjectUtil.isNullOrEmpty(dto.getApplyPackQty())) {
                line.setApplyPackQty(ParseUtil.tryLongWithException(dto.getApplyPackQty()));
            }
            if (!ObjectUtil.isNullOrEmpty(dto.getApplyWeight())) {
                line.setApplyWeigth(new BigDecimal(dto.getApplyWeight()));
            }
            if (!ObjectUtil.isNullOrEmpty(dto.getFromAreaId())) {
                line.setWmAreaId(ParseUtil.tryLongWithException(dto.getFromAreaId()));
            }
            if (!ObjectUtil.isNullOrEmpty(dto.getFromLocationId())) {
                line.setLocationId(ParseUtil.tryLongWithException(dto.getFromLocationId()));
            }
            if (!ObjectUtil.isNullOrEmpty(dto.getToLocationId())) {
                line.setToLocationId(ParseUtil.tryLongWithException(dto.getToLocationId()));
            }
            if (!ObjectUtil.isNullOrEmpty(dto.getToAreaId())) {
                line.setToWmAreaId(ParseUtil.tryLongWithException(dto.getToAreaId()));
            }
            if (!ObjectUtil.isNullOrEmpty(dto.getViaAreaId())) {
                line.setViaWmAreaId(ParseUtil.tryLongWithException(dto.getViaAreaId()));
            }
            if (!ObjectUtil.isNullOrEmpty(dto.getViaLocationId())) {
                line.setViaLocationId(ParseUtil.tryLongWithException(dto.getViaLocationId()));
            }
            lines.add(line);
        }
        checkResult.setData(lines);
        return checkResult;
    }

    /**
     * 创建领料单执行
     *
     * @param lins     领料单行信息
     * @param headerId 领料单头Id
     * @param eventId  事件ID
     * @return WmExecuteLine
     **/
    @Override
    public CheckResult<List<WmExecuteLine>> createExecuteLine(List<WmRequestLine> lins, Long headerId, Long eventId) {
        CheckResult<List<WmExecuteLine>> checkResult = new CheckResult<>();
        checkResult.setSuccessful(true);
        List<WmExecuteLine> executeLines = new ArrayList<>();
        for (WmRequestLine dto : lins) {
            WmExecuteLine line = new WmExecuteLine();
            line.setEventId(eventId);
            line.setItemId(dto.getItemId());
            line.setUom(dto.getUom());
            line.setDocumentLineId(dto.getId());
            line.setExecuteType(AllotConstrants.EXECUTE_TYPE);
            line.setExecutedQty(dto.getApplyQty());
            line.setExecutedTime(new Date());
            line.setDocumentId(headerId);
            line.setDocumentType(AllotConstrants.REQUEST_TYPE);
            line.setLotNumber(dto.getLotNumber());
            line.setTagCode(dto.getTagCode());
            line.setOwnerType(dto.getOwnerType());
            line.setWarehouseId(dto.getWarehouseId());
            line.setToWarehouseId(dto.getToWarehouseId());
            BdTag tag = new BdTag()
                    .selectOne(new EntityWrapper()
                            .eq(BdTag.TAG_CODE, dto.getTagCode()));
            if (!ObjectUtil.isEmpty(tag)) {
                line.setWmAreaId(tag.getId());
            }
            line.setWmAreaId(dto.getWmAreaId());
            line.setLocationId(dto.getLocationId());
            line.setToLocationId(dto.getToLocationId());
            line.setToWmAreaId(dto.getToWmAreaId());
            line.setOwnerId(dto.getOwnerId());
            executeLines.add(line);
        }
        checkResult.setData(executeLines);

        return checkResult;
    }
}
